package myself.study.network.tcp.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @Name: TcpServer
* @Description: tcp协议通信服务端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午12:43:28 
* @Version: V1.0
 */
public class TcpServer {
	
	public static void main(String[] args) throws IOException, InterruptedException {
		//创建服务端Socket对象
		ServerSocket server = new ServerSocket(12345) ;
		System.out.println("tcp服务器启动...");
		Socket socket = null ;
		while(true) {
			try {
				//监听客户端连接
				socket = server.accept() ;  //阻塞1
				//获取输入流对象，接收客户端发送过来的数据
				InputStream inputStream = socket.getInputStream() ;
				byte[] buf = new byte[1024] ;
				int len = inputStream.read(buf) ; //阻塞2
				String requestData = new String(buf, 0, len) ;
				//获取客户端ip地址
				String hostAddress = socket.getInetAddress().getHostAddress() ;
				System.out.println("from client -> " + hostAddress + " : " + requestData);
				//处理客户端发送的请求
				//休眠2秒
				Thread.sleep(2000) ;
				//处理结果
				String responseData = "知道了，忙你自己的事吧！" ;
				//获取输入流对象，向客户端响应处理结果
				OutputStream outputStream = socket.getOutputStream() ;
				outputStream.write(responseData.getBytes()) ;
				System.out.println("to client -> " + hostAddress + " : " + responseData);
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				//释放资源
				if(socket != null) {
					socket.close() ;
				}
			}
		}
	}

}
